/**
 * Copyright(c) 2010 Ceno Techonologies Co., Ltd.
 *
 * History:
 *   15-6-5 下午3:23 Created by lyyang
 */
package com.jade.bss.business.coupon.impl;

import java.util.List;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.jade.bss.business.coupon.CouponDao;
import com.jade.bss.business.coupon.CouponInfo;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.sql.SqlUtils;
import com.jade.framework.base.util.PagingList;

/**
 * 卡券dao,jpa实现
 *
 * @author <a href="mailto:lyyang@ceno.cn">lyyang</a>
 * @version 1.0 15-6-5 下午3:23
 */
@Named ("bss_couponDao")
public class JpaCouponDao
        implements CouponDao
{
    @PersistenceContext (unitName = "default")
    protected EntityManager entityManager;

    public CouponInfo add(CouponInfo base)
    {
        entityManager.persist(base);
        return base;
    }

    public CouponInfo get(long id)
    {
        return entityManager.find(CouponInfo.class, id);
    }

    public void update(CouponInfo base)
    {
        entityManager.merge(base);
    }

    public void remove(CouponInfo base)
    {
        entityManager.remove(base);
    }

    public PagingList<CouponInfo> query(Criteria criteria)
    {
        String sql = "SELECT coupon FROM CouponInfo coupon";
        return SqlUtils.sqlQuery(sql, entityManager, criteria);
    }

    public List<CouponInfo> list(Criteria criteria)
    {
        String sql = "SELECT coupon FROM CouponInfo coupon";
        return SqlUtils.sqlQueryWithoutCount(sql, entityManager, criteria);
    }

    public void increaseQuantity(String id, long quantity)
    {
        String sql = "UPDATE CouponInfo SET quantity=quantity+:quantity WHERE cardId=:cardId";
        Query query = entityManager.createQuery(sql);
        query.setParameter("cardId", id);
        query.setParameter("quantity", quantity);
        query.executeUpdate();

    }

    public CouponInfo get(String cardId)
    {
        String sql = "SELECT coupon FROM CouponInfo coupon WHERE cardId=:cardId";
        Query query = entityManager.createQuery(sql);
        query.setParameter("cardId", cardId);
        try {
            return (CouponInfo) query.getSingleResult();
        }
        catch (NoResultException ex) {
            return null;
        }
    }

    public CouponInfo getByFid(String fid)
    {
        String sql = "SELECT coupon FROM CouponInfo coupon WHERE fid=:fid";
        Query query = entityManager.createQuery(sql);
        query.setParameter("fid", fid);
        try {
            return (CouponInfo) query.getSingleResult();
        }
        catch (NoResultException ex) {
            return null;
        }
    }
}
